#include"service.h"
#include"globalinfo.h"
#include<time.h>
#include<sstream>
#include<iostream>
#include<vector>
CliService cliService;
void CliService::registerCmd(CliTaskExecutor * executor)  {
    std::cout << "Register Command:\t" << executor->getCmdName() << std::endl;
    if(this->taskMap.count(executor->getCmdName()) != 0) {
        std::cerr << "Command \"" << executor->getCmdName()  << "\" register failed" << std::endl;
        throw Exception("cmdName conflict");
    }
    this->taskMap[executor->getCmdName()] = executor;
}

void CliService::executeCmd(std::string cmd)  {
    try {
        std::istringstream stream(cmd);
        std::string t;
        std::vector<std::string> args;
        // 按空格分割
        while ( stream >> t ) {
            args.push_back(t);
        }
        if(args.size() == 0) {
            return;
        }
        // 检查命令是否存在
        if(this->taskMap.count(args[0]) == 0) {
            throw Exception("command not found");

        }
        // 执行命令任务
        this->taskMap[args[0]]->cmdTask(args);
    } catch(const Exception& e) {
        std::cerr << e.what() << '\n';
    }
}

void CliService::start() {
    char input[8192];
    while(1) {
        printf("[%s]> ", globalInfo.path.getPath().c_str());
        try {
            memset(input, 0, sizeof(input));
            std::cin.getline(input, 8192);
            cliService.executeCmd(std::string(input));
        } catch(const Exception& e) {
            std::cout << "123" << std::endl;
            std::cerr << e.what() << '\n';
        } catch(...) {
            std::cerr << "Command execute failed" << '\n';
        }
    }

}